<?php

namespace app\admin\controller;

use app\admin\logic\IndexLogic;
use app\BaseController;
use think\exception\ValidateException;
use think\facade\Cache;
use think\facade\Cookie;
use think\facade\Request;
use think\facade\Session;
use think\facade\View;

class Login extends BaseController
{
    //为了防止跳页死循环(初始化为空顶)
    protected function initialize()
    {
    }
    //登录页面
    public function login()
    {
        $free = Request::get('free', '');
        if ($free != 'no') {
            $user_free = Cookie::get('user_free');
            if (isset($user_free) && !empty($user_free)) {
                $arr = explode("_", Cookie::get('user_free'));
                $find = \app\admin\model\Users::find($arr[0]);
                if ($find) {
                    $uname_upwd = md5($find['uname']) . md5($find['upwd']);
                    if (end($arr) == $uname_upwd) {
                        View::assign('logo', $find['logo']);
                        View::assign('id', $find['id']);
                        return View::fetch('login_free');
                    }
                }
            }
        }
        return View::fetch();
    }

    //登录跳转页面
    public function loginIn()
    {
        if (Request::isPost()) {
            $post = Request::post();
            //账号和密码错误次数
            $num = Cache::get($post['uname']);
            //错误时间为一小时之内(账号和密码错误次数)
            $error_time = Cache::get($post['uname'] . '_time');
            //当账号和密码错误5次时禁止当天登录
            $error_times = Cache::get($post['uname'] . '_times');
            if ($num >= 5 && $error_times > time()) {
                $this->error('账号与密码错误' . $num . '次,请在 ' . date("Y-m-d H:i:s", $error_times) . '后登录', url('login/login'), '', $error_times);
            }
            if ($num >= 3 && $error_time > time()) {
                try {
                    validate(\app\validate\login::class)->scene('show_code')
                        ->check($post);
                } catch (ValidateException $e) {
                    $this->error($e->getError());
                }
            }else{
                try {
                    validate(\app\validate\login::class)->scene('hide_code')
                        ->check($post);
                } catch (ValidateException $e) {
                    $this->error($e->getError());
                }
            }
            $res = \app\admin\model\Login::loginInfo($post);
            if ($res) {
                Session::set('user', $res);
                Session::set('user_id', $res['id']);
                //当选择三十天免登录复选框时 添加Cookie
                if (isset($post['free']) && !empty($post['free'])) {
                    $uname_upwd = $res['id'] . '_' . md5($res['uname']) . md5($res['upwd']);
                    Cookie::set('user_free', $uname_upwd, 2592000);
                }
                Cache::delete($post['uname']);
                $this->success('登录成功', url('index/index'));
            } else {
                //登录五次之后拒绝当天登录
                if ($num >= 4) {
                    if (!Cache::has($post['uname'] . '_times') && empty(Cache::get($post['uname'] . '_times'))) {
                        Cache::set($post['uname'] . '_times', time() + 86400);
                        Cache::set($post['uname'], 5, 86400);
                    }
                } else {
                    //登录三次后出现验证码
                    //使用缓存自增功能
                    Cache::inc($post['uname']);
                    if (!Cache::has($post['uname'] . '_time') && empty(Cache::get($post['uname'] . '_time'))) {
                        Cache::set($post['uname'] . '_time', time() + 3600);
                    }
                }
                $this->error('账号或密码错误:' . ($num + 1) . '次', url('login/login'));
            }
        } else {
            return View::fetch();
        }
    }

    //三十天免登录
    public function loginFree()
    {
        $arr = explode("_", Cookie::get('user_free'));
        $find = \app\admin\model\Users::find($arr[0]);
        View::assign($find->toArray());
        Session::set('user', $find);
        Session::set('user_id', $find['id']);
        $uname_upwd = md5($find['uname']) . md5($find['upwd']);
        $get = Request::get();
        if (isset($get['id']) && !empty($get['id'])) {
            if (end($arr) == $uname_upwd) {
                $this->success('登录成功', url('index/index'));
            } else {
                $this->error('登录失败');
            }
        }

        return View::fetch();
    }

    //退出登录
    public function loginOut()
    {
        Session::delete('user');
        Session::delete('user_id');
        $user_free = Cookie::get('user_free');
        if (isset($user_free) && !empty($user_free)) {
            $arr = explode("_", Cookie::get('user_free'));
            $find = \app\admin\model\Users::find($arr[0]);
            if ($find) {
                $uname_upwd = md5($find['uname']) . md5($find['upwd']);
                if (end($arr) == $uname_upwd) {
                    $this->success('退出成功', url('login/loginFree'));
                }else{
                    $this->error('退出成功', url('login/login'));
                }
            }
        }else{
            $this->error('退出成功', url('login/login'));
        }
    }

    //账号或者密码错误三次出现验证码ajax
    public function ajaxUnameCount()
    {
        $uname = Request::post('uname');
        //账号和密码错误次数
        $num = Cache::get($uname);
        //错误时间为一小时之内(账号和密码错误次数)
        $error_time = Cache::get($uname . '_time');
        if ($num >= 3 && $error_time > time()) {
            return json(['status' => true]);
        };
        return json(['status' => false]);

    }

    //验证码是否正确登录按钮是否禁用ajax(开启session!!!!!!!!)
    public function ajaxCode()
    {
        $code = Request::post('code');
        if (!captcha_check($code, false)) {
            return json(['status' => false]);
        };
        return json(['status' => true]);
    }





    //验证码修改密码
     public function loginFile(){

        if (Request::isPost()){
            $post=Request::post();
            if (Cache::has('send_yzm') && !empty(Cache::get('send_yzm'))){
              if (Session::has('file_yzm') && !empty(Session::get('file_yzm'))){
                  $file_yzm=Session::get('file_yzm');
                  if ($file_yzm==$post['yzm']){
                      $list=Session::get('user')->toArray();
                      $find=\app\admin\model\Users::find($list['id'])->toArray();
                     if ($find['upwd']!=md5($post['old_pwd'])){
                         $this->error('原密码不正确');
                     }
                     if (!empty($find['email'])){
                         $res=\app\admin\model\Users::where('id','=',$find['id'])->update(['upwd'=>md5($post['new_pwd'])]);
                     }else{
                         $res=\app\admin\model\Users::where('id','=',$find['id'])->update(['upwd'=>md5($post['new_pwd']),'email'=>$post['email']]);
                     }
                     if ($res){
                         $this->success('修改成功',url('login/login'));
                     }else{
                         $this->error('修改失败',url('login/loginfile'));
                     }
                  }else{
                      $this->error('验证码错误',url('login/loginfile'));
                  }
              }
            }else{
                $this->error('验证码过期无效',url('login/loginfile'));
            }
        }else{
            $list=Session::get('user')->toArray();
            View::assign($list);
            return View::fetch();
        }
      }
    //验证码邮箱ajax
     public function ajaxFile(){
         $email=Request::post('email');
         $yzm=rand(1000,9999);
         $res=SendFile::sendFileInfo($email,'修改密码验证码',$yzm);
         if ($res){
             return 0;
         }else{
             return 1;
         }
      }








}